package org.cainiao.servlet.concurrent.service.impl;

import lombok.RequiredArgsConstructor;
import org.cainiao.servlet.concurrent.service.OrderService;
import org.cainiao.servlet.concurrent.util.lock.RedisDistributedLock;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final RedisDistributedLock redisDistributedLock;

    private static final String LOCK_KEY_PREFIX = "lock:order:";
    private static final long LOCK_EXPIRE_TIME = 30000; // 30秒
    private static final long LOCK_WAIT_TIME = 5000;    // 最大等待5秒
    private static final long POLL_INTERVAL = 100;      // 轮询间隔100ms

    @Override
    public void processOrder(String orderId) {
        String lockKey = LOCK_KEY_PREFIX + orderId;
        String lockValue = UUID.randomUUID().toString(); // 唯一标识

        try {
            // 尝试获取锁，轮询等待
            boolean locked = redisDistributedLock.lock(
                lockKey,
                lockValue,
                LOCK_EXPIRE_TIME,
                LOCK_WAIT_TIME,
                POLL_INTERVAL
            );

            if (locked) {
                // 执行业务代码
                System.out.println("成功获取锁，处理订单: " + orderId);
                // ...
            } else {
                System.out.println("获取锁超时，处理失败");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("线程被中断");
        } finally {
            // 确保释放锁
            redisDistributedLock.unlock(lockKey, lockValue);
        }
    }
}
